package com.gzw.shop.activity;

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gzw.shop.App;
import com.gzw.shop.Contans;
import com.gzw.shop.R;
import com.gzw.shop.bean.User;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;
import com.gzw.shop.msg.LoginRespMsg;
import com.gzw.shop.utils.CountTimerView;
import com.gzw.shop.utils.DESUtil;
import com.gzw.shop.utils.ToastUtils;
import com.gzw.shop.widget.ClearEditText;
import com.gzw.shop.widget.GToolbar;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
import dmax.dialog.SpotsDialog;
import okhttp3.Response;

public class RegSecondActivity extends BaseActivity {


    @BindView(R.id.toolbar)
    GToolbar toolbar;
    @BindView(R.id.txtTip)
    TextView txtTip;
    @BindView(R.id.edittxt_code)
    ClearEditText edittxtCode;
    @BindView(R.id.btn_reSend)
    Button btnReSend;

    private String phone;
    private String pwd;
    private String countryCode;

    private CountTimerView countTimerView;


    private SpotsDialog dialog;

    private EventHandler handler;

    private OkHttpHelper okHttpHelper = OkHttpHelper.getInstance();

    @Override
    public int getLayoutId() {
        return R.layout.activity_reg_second;
    }

    @Override
    public void initView() {

        toolbar.setRightBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitCode();
            }
        });

    }

    @Override
    public void initData() {

        phone = getIntent().getStringExtra("phone");
        pwd = getIntent().getStringExtra("pwd");
        countryCode = getIntent().getStringExtra("countryCode");

        String formatedPhone = "+" + countryCode + " " + splitPhoneNum(phone);

        String text = getString(R.string.smssdk_send_mobile_detail) + formatedPhone;
        txtTip.setText(Html.fromHtml(text));

        CountTimerView timerView = new CountTimerView(btnReSend);
        timerView.start();

        SMSSDK.initSDK(this, "1da1aa6484568", "9ce9367ab2e3b01700c8f08ce046a7cb");

        handler = new EventHandler() {
            @Override
            public void afterEvent(final int event, final int result,
                                   final Object data) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (dialog != null && dialog.isShowing())
                            dialog.dismiss();

                        if (result == SMSSDK.RESULT_COMPLETE) {
                            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {

                                doReg();
                                dialog.setMessage("正在提交注册信息");
                                dialog.show();
                            }
                        } else {

                            // 根据服务器返回的网络错误，给toast提示
                            try {
                                ((Throwable) data).printStackTrace();
                                Throwable throwable = (Throwable) data;

                                JSONObject object = new JSONObject(
                                        throwable.getMessage());
                                String des = object.optString("detail");
                                if (!TextUtils.isEmpty(des)) {
//                                ToastUtils.show(RegActivity.this, des);
                                    return;
                                }
                            } catch (Exception e) {
                                SMSLog.getInstance().w(e);
                            }
                        }
                    }
                });
            }
        };

        SMSSDK.registerEventHandler(handler);

        dialog = new SpotsDialog(this);
        dialog = new SpotsDialog(this, "正在校验验证码");

    }

    @OnClick(R.id.btn_reSend)
    public void reSendCode(View view) {

        SMSSDK.getVerificationCode("+" + countryCode, phone);
        countTimerView = new CountTimerView(btnReSend, R.string.smssdk_resend_identify_code);
        countTimerView.start();

        dialog.setMessage("正在重新获取验证码");
        dialog.show();
    }


    /**
     * 分割号码
     *
     * @param phone
     * @return
     */
    private String splitPhoneNum(String phone) {
        StringBuilder builder = new StringBuilder(phone);
        builder.reverse();
        for (int i = 4, len = builder.length(); i < len; i += 5) {
            builder.insert(i, ' ');
        }
        builder.reverse();
        return builder.toString();
    }

    private void doReg() {

        Map<String, Object> params = new HashMap<>(2);
        params.put("phone", phone);
        params.put("password", DESUtil.encode(Contans.DES_KEY, pwd));

        okHttpHelper.post(Contans.API.REG, params, new SpotsCallBack<LoginRespMsg<User>>(this) {

            @Override
            public void onSuccess(Response response, LoginRespMsg<User> userLoginRespMsg) {

                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                if (userLoginRespMsg.getStatus() == LoginRespMsg.STATUS_ERROR) {
                    ToastUtils.show(RegSecondActivity.this, "注册失败:" + userLoginRespMsg.getMessage());
                    return;
                }
                App application = App.getInstance();
                application.putUser(userLoginRespMsg.getData(), userLoginRespMsg.getToken());
                startActivity(new Intent(RegSecondActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onTokenError(Response response, int code) {
                super.onTokenError(response, code);
            }
        });

    }

    /**
     * 提交验证码
     */
    private void submitCode() {

        String vCode = edittxtCode.getText().toString().trim();

        if (TextUtils.isEmpty(vCode)) {
            ToastUtils.show(this, R.string.smssdk_write_identify_code);
            return;
        }
        SMSSDK.submitVerificationCode(countryCode, phone, vCode);
        dialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(handler);
    }
}
